package cn.zebra.dev.oss.module.tencent.service;

import cn.zebra.dev.config.oss.tencent.TenCentOssConfigureBean;
import cn.zebra.dev.oss.module.base.service.BaseOssService;
import com.alibaba.fastjson.JSONObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.request.UploadFileRequest;
import com.qcloud.cos.sign.Credentials;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author runnable@sina.cn
 */
@Service
public class TenCentOssServiceImpl implements BaseOssService {

    private COSClient client;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private TenCentOssConfigureBean configureBean;

    /**
     * 获取腾讯云客户端配置(懒汉初始化)
     *
     * @return 腾讯云客户端配置
     */
    private COSClient getClient() {
        if (client == null) {
            synchronized (this) {
                if (client == null) {
                    ClientConfig clientConfig = new ClientConfig();
                    Credentials credentials = new Credentials(configureBean.getAppId(), configureBean.getSecretId(), configureBean.getSecretKey());
                    clientConfig.setRegion(configureBean.getRegion());
                    client = new COSClient(clientConfig, credentials);
                }
            }
        }
        return client;
    }

    @Override
    public String upload(byte[] data, String path) {
        //腾讯云必需要以"/"开头
        if (!path.startsWith("/")) {
            path = "/" + path;
        }

        //上传到腾讯云
        UploadFileRequest request = new UploadFileRequest(configureBean.getBucketName(), path, data);
        String response = getClient().uploadFile(request);

        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getInteger("code") != 0) {
            logger.error(jsonObject.getString("message"));
            throw new RuntimeException("文件上传失败!");
        }

        return configureBean.getDomain() + path;
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败", e);
        }
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(configureBean.getPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(configureBean.getPrefix(), suffix));
    }
}
